package com.huaruan.youdi.views.activitys;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.menu.MenuItemImpl;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import butterknife.ButterKnife;

import com.huaruan.youdi.R;
import com.huaruan.youdi.utils.AppManager;
import com.huaruan.youdi.utils.AppUtils;
import com.huaruan.youdi.views.IActivityHelper;

import com.gyf.barlibrary.BarHide;
import com.gyf.barlibrary.ImmersionBar;
import com.huaruan.youdi.views.OnFastClickListener;


public abstract class BaseActivity extends AppCompatActivity implements IActivityHelper {
    private Toolbar toolbar;
    private TextView toolbarTitle;
    private View toolbarClose;
    private Handler handler;
    MenuItemImpl messageMenuItem;
    private MenuItemImpl overFlowMenuItem;
    //RxJava
    public ImmersionBar mImmersionBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        beforeSetContentView();
        AppManager.getAppManager().addActivity(this);
        if (IGetMultiSatesContentViewResId() != 0) {
            View rootView = View.inflate(IGetContext(), R.layout.base_multistate_layout, null);
            ((ViewGroup) rootView.findViewById(R.id.content)).addView(View.inflate(IGetContext(),
                    IGetMultiSatesContentViewResId(), null));
            setContentView(rootView);
        } else if (IGetContentView() != null)
            setContentView(IGetContentView());
        else if (IGetContentViewResId() != 0) {
            setContentView(IGetContentViewResId());
        } else setContentView(R.layout.activity_base_contain_fragment);
        if (isFullScreenAndHideStatusBar()) {
            mImmersionBar = ImmersionBar.with(this)
                    .fullScreen(true)
                    .statusBarDarkFont(isStatusBarDarkFont())
                    .statusBarColor(R.color.transparent_color)
                    .hideBar(BarHide.FLAG_HIDE_STATUS_BAR);
        } else if (isFullScreen()) {
            mImmersionBar = ImmersionBar.with(this)
                    .fullScreen(true)
                    .statusBarColor(R.color.transparent_color)
                    .statusBarDarkFont(isStatusBarDarkFont());
        } else if (HideStatusBar()) {
            mImmersionBar = ImmersionBar.with(this)
                    .statusBarColor(R.color.transparent_color)
                    .statusBarDarkFont(isStatusBarDarkFont());
        } else {//default
            mImmersionBar = ImmersionBar.with(this).fitsSystemWindows(true).statusBarColor(getStatusBarColorResId()).statusBarDarkFont(isStatusBarDarkFont());
        }
        mImmersionBar.navigationBarColorInt(getNavigationBarColor());
        mImmersionBar.keyboardEnable(true);
        mImmersionBar.init();
        ButterKnife.bind(this);
        View view = findViewById(R.id.toolbar);
        View title = findViewById(R.id.toolbarTitle);
        View close = findViewById(R.id.toolbarClose);
        if (title != null) {
            toolbarTitle = (TextView) title;
            toolbarTitle.setText(getTitle());
        }
        if (close != null) {
            toolbarClose = close;
            close.setOnClickListener(new OnFastClickListener() {
                @Override
                public void onFastClick(View v) {
                    finish();
                }
            });
        }
        if (view != null) {
            toolbar = (Toolbar) view;
            toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
//                    if (item.getItemId() == R.id.home)
//                        AppUtils.JumpToHome(IGetActivity());
//                    else if (item.getItemId() == R.id.center) {
//                        Intent toCenter = new Intent(IGetContext(), MainActivity.class);
//                        toCenter.putExtra("to", "center");
//                        startActivity(toCenter);
//                    } else if (item.getItemId() == R.id.message) {
//                        AppUtils.JumpToMessagePage(IGetContext(), null);
//                    } else
                        onItemClick(item);
                    return true;
                }
            });
            if (isShowBackButton()) {
                setNavigation(toolbar);
            }
        }
        IFindViews();
        IInitData();
        IRequest();
        if (isShowDefaultOverflowMenu())
            initToolbarRightMenu();
    }

    public int getStatusBarColorResId() {
        //default
        return R.color.color_white;
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    /**
     * 设置导航按钮
     *
     * @param toolbar
     */
    public void setNavigation(Toolbar toolbar) {
        if (toolbar == null)
            return;
        if(isShowBackButtonWhite()){
            toolbar.setNavigationIcon(R.mipmap.ic_action_previous_item_white);
        }else{
            toolbar.setNavigationIcon(R.mipmap.ic_action_previous_item_black);
        }
        toolbar.setNavigationOnClickListener(new OnFastClickListener() {
            @Override
            public void onFastClick(View v) {
                AppUtils.hideSoftInput(IGetActivity());
                onBackPressed();
            }
        });
    }

    public void beforeSetContentView() {
    }

    /**
     * 初始化导航菜单栏
     */
    public void initToolbarRightMenu() {
        if (toolbar == null)
            return;
        toolbar.inflateMenu(R.menu.toolbar_right_menu);
        overFlowMenuItem = (MenuItemImpl) toolbar.getMenu().findItem(R.id.overFlow);
        messageMenuItem = (MenuItemImpl) getToolbar().getMenu().findItem(R.id.message);
    }

    /**
     * @param item
     */
    public void onItemClick(MenuItem item) {

    }

    @Override
    public Context IGetContext() {
        return this;
    }

    @Override
    public Activity IGetActivity() {
        return this;
    }

    /**
     * 多状态基类布局，比如内容加载等待状态，数据请求失败状态等等。。。
     *
     * @return
     */
    @Override
    public int IGetMultiSatesContentViewResId() {
        return 0;
    }

    @Override
    public abstract int IGetContentViewResId();

    @Override
    public View IGetContentView() {
        return null;
    }

    @Override
    public abstract void IFindViews();

    @Override
    public void IFindViews(View view) {

    }

    @Override
    public abstract void IInitData();

    @Override
    public void IRequest() {
        showContentLoadingView();
    }

    @Override
    public void lazyLoad() {

    }

    public Toolbar getToolbar() {
        return toolbar;
    }

    public void setToolbar(Toolbar toolbar) {
        this.toolbar = toolbar;
    }

    public TextView getToolbarTitle() {
        return toolbarTitle;
    }

    public View getToolbarClose() {
        return toolbarClose;
    }

    /**
     * 默认显示页面overflow menu,并且显示默认的item menu
     *
     * @return
     */
    public boolean isShowDefaultOverflowMenu() {
        return false;
    }

    /**
     * 默认显示页面后退键,默认显示
     *
     * @return
     */
    public boolean isShowBackButton() {
        return true;
    }

    /**
     * 默认显示页面后退键,默认显示
     *
     * @return
     */
    public boolean isShowBackButtonWhite() {
        return false;
    }


    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        AppUtils.hideSoftInput(this);
        super.onDestroy();
        AppManager.getAppManager().remove(this);
        if (mImmersionBar != null)
            mImmersionBar.destroy();
    }

    /**
     * 移除消息菜单栏
     */
    public void removeMessageMenuItem() {
        if (toolbar == null)
            return;
        toolbar.getMenu().findItem(R.id.overFlow).setIcon(R.mipmap.ic_action_overflow);
        if (toolbar.getMenu().getItem(0).getSubMenu().findItem(R.id.message) != null)
            toolbar.getMenu().getItem(0).getSubMenu().removeItem(R.id.message);
        messageMenuItem = null;
    }

    public void addShareMenuItem() {
        if (getToolbar() == null || getToolbar().getMenu() == null || getToolbar().getMenu().size
                () == 0)
            return;
        MenuItem menuItem = getToolbar().getMenu().getItem(getToolbar().getMenu().size() - 1)
                .getSubMenu().add(Menu.NONE, R.id.menu_share, 23, "分享");
        menuItem.setIcon(R.mipmap.icon_action_share);
    }

    public Handler getHandler() {
        if (handler == null)
            handler = new Handler(Looper.getMainLooper());
        return handler;
    }

    /**
     * 显示内容正在加载，全屏的(默认显示)
     */
    public void showContentLoadingView() {
        if (findViewById(R.id.shloading) != null)
            findViewById(R.id.shloading).setVisibility(View.VISIBLE);
    }

    @Deprecated
    public void hideContentLoadingView() {
        if (findViewById(R.id.shloading) != null)
            findViewById(R.id.shloading).setVisibility(View.GONE);
    }

    /**
     * 显示内容加载失败，全屏的
     */
    public void showLoadFailAndRetryView(View.OnClickListener onClickListener) {
        if (findViewById(R.id.loadFailAndRetry) != null) {
            hideContentLoadingView();
            findViewById(R.id.loadFailAndRetry).setVisibility(View.VISIBLE);
            findViewById(R.id.base_retry).setOnClickListener(onClickListener);
        }
    }

    /**
     * 用{@link #hideLoadingAndRetryView()}代替
     */
    @Deprecated
    public void hideLoadFailAndRetryView() {
        if (findViewById(R.id.loadFailAndRetry) != null)
            findViewById(R.id.loadFailAndRetry).setVisibility(View.GONE);
    }

    /**
     * 同时隐藏内容加载和加载失败重试view
     */
    public void hideLoadingAndRetryView() {
        hideContentLoadingView();
        hideLoadFailAndRetryView();
    }

    /**
     * 是否开启右滑关闭功能,默认开启
     *
     * @return
     */
    public boolean isSwipeBackEnable() {
        return false;
    }

    /**
     * 是否开启全屏侧滑关闭，默认全屏,否则80dp
     * ps.此方法在5.2.5之后的版本才生效
     *
     * @return
     */
    public boolean isSwipeBackFullScreenEnable() {
//        return !"5.2.5".equalsIgnoreCase(AppUtils.getVersionName(IGetContext()));
        return false;//暂时关闭，如有需要再开启
    }

    /**
     * 是否开启全屏模式,状态栏会覆盖在上面
     *
     * @return
     */
    public boolean isFullScreen() {
        return false;
    }

    /**
     * 开启全屏模式，是否同时隐藏状态栏，默认不隐藏,优先级最高
     *
     * @return
     */
    public boolean isFullScreenAndHideStatusBar() {
        return false;
    }

    public boolean HideStatusBar() {
        return false;
    }

    /**
     * 状态栏字体是否深色，默认深色
     *
     * @return
     */
    public boolean isStatusBarDarkFont() {
        return true;
    }

    /**
     * 获取底部导航栏颜色
     *
     * @return
     */
    public int getNavigationBarColor() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? getWindow().getNavigationBarColor() : ContextCompat.getColor(IGetContext(), R.color.color_white);
    }
}